package cn.broadsense.common.validator;

import cn.broadsense.common.annotation.ValueInEnum;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @author huangjinshi
 * @description
 * @createDate 2024-09-20 10:43:07
 */
public class ValueInEnumValidator implements ConstraintValidator<ValueInEnum, Object> {

    private String[] allowedStringValues;
    private int[] allowedIntValues;

    @Override
    public void initialize(ValueInEnum constraintAnnotation) {
        allowedStringValues = constraintAnnotation.allowedStringValues();
        allowedIntValues = constraintAnnotation.allowedIntValues();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value == null) {
            return true; // Consider null as valid. You can change this behavior if needed.
        }
        if (value instanceof String) {
            for (String allowedValue : allowedStringValues) {
                if (allowedValue.equals(value)) {
                    return true;
                }
            }
        } else if (value instanceof Integer) {
            for (int allowedValue : allowedIntValues) {
                if (allowedValue == (Integer) value) {
                    return true;
                }
            }
        }
        return false;
    }
}
